package com.hoperun.product.activity;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.hoperun.product.Models.UserModel;
import com.hoperun.product.Models.ZhenshaModel;
import com.hoperun.product.base.MIP_BaseActivity;
import com.hoperun.product.net.IServiceImpl;
import com.hoperun.product.net.RequestServiceImpl;
import com.hoperun.product.util.ParseUtils;
import com.hoperun.product.util.SharedPreUtil;
import com.hoperun.product.view.SimpleDialog;
import com.hoperun.product.wgyutil.WgyUtil;
import com.hoperun.yieldmgr.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ZhenShaActivity extends MIP_BaseActivity {

    @BindView(R.id.input_dateTv)
    TextView inputDateTv;
    @BindView(R.id.input_dateLl)
    LinearLayout inputDateLl;

    @BindView(R.id.qu_zhibie)
    EditText quZhibie;
    @BindView(R.id.qu_chehao)
    EditText quChehao;
    @BindView(R.id.recylistview)
    RecyclerView recylistview;

    QuickAdapter quickAdapter;
    ArrayList<ZhenshaModel> daolist = new ArrayList<ZhenshaModel>();
    ArrayList<ZhenshaModel> deletedaolist = new ArrayList<ZhenshaModel>();
    ArrayList<ZhenshaModel> savedaolist = new ArrayList<ZhenshaModel>();
    @BindView(R.id.qu_pihao)
    EditText quPihao;
    @BindView(R.id.query_zhibie)
    EditText queryZhibie;
    @BindView(R.id.query_pihao)
    EditText queryPihao;
    @BindView(R.id.qu_ganghao)
    EditText quGanghao;

    private int mCount = 0;
    //日期
    String mJobDate;
    private SimpleDateFormat dateFormat_ZH = new SimpleDateFormat("yyyy年MM月dd日");
    private SimpleDateFormat dateFormat_EN = new SimpleDateFormat("yyyy-MM-dd");

    UserModel userModel = null;
    EditDialogZhen.Builder dialog = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zhen_sha);
        ButterKnife.bind(this);
        try {
            String jsonuser = SharedPreUtil.getValue(this, SharedPreUtil.USERBEAN, "").toString();
            userModel = ParseUtils.parse(jsonuser, UserModel.class);
            mJobDate = userModel.getJobDate();//dateFormat_EN.format(new Date(System.currentTimeMillis()));
            inputDateTv.setText(dateFormat_ZH.format(dateFormat_EN.parse(userModel.getJobDate())));
        } catch (Exception e) {
        }


        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recylistview.setLayoutManager(layoutManager);
        //给RecyclerView设置适配器
        quickAdapter = new QuickAdapter();
        recylistview.setAdapter(quickAdapter);
        //默认查
        querylist(mJobDate, "", "");

    }

    public class QuickAdapter extends BaseQuickAdapter<ZhenshaModel, BaseViewHolder> {
        public QuickAdapter() {
            super(R.layout.zhen_list_item, daolist);
        }


        @Override
        protected void convert(final BaseViewHolder holder, ZhenshaModel item) {
            TextView item_banci = holder.getView(R.id.item_banci);//班次
            final EditText input_zhenbanci = holder.getView(R.id.input_zhenbanci);//蒸班次
            TextView item_gonghao = holder.getView(R.id.item_gonghao);//工号
            TextView item_zhibie = holder.getView(R.id.item_zhibie);//支别
            TextView item_shazhiquan = holder.getView(R.id.item_shazhiquan);//纱支全称
            TextView item_sehao = holder.getView(R.id.item_sehao);//色号
            TextView item_gonghuodanwei = holder.getView(R.id.item_gonghuodanwei);//供货单位
            TextView item_pihao = holder.getView(R.id.item_pihao);//批号
            final EditText input_shuliang = holder.getView(R.id.input_shuliang);//
            CheckBox input_item_checkBox = holder.getView(R.id.input_item_checkBox);

            input_item_checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    daolist.get(holder.getLayoutPosition()).setBoxcheck(isChecked);
//                    mCount = 0;
//                    for (int i = 0; i < daolist.size(); i++) {
//                        if (daolist.get(i).isBoxcheck() == true) {
//                            mCount++;
//                        }
//                    }
                }
            });
            input_shuliang.addTextChangedListener(new TextWatcher() {

                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    daolist.get(holder.getLayoutPosition()).setPACKNUM(input_shuliang.getText().toString());
                }

                @Override
                public void afterTextChanged(Editable editable) {

                }
            });
            input_zhenbanci.addTextChangedListener(new TextWatcher() {
                private int selectionStart;
                private int selectionEnd;

                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    daolist.get(holder.getLayoutPosition()).setSTCLASS(input_zhenbanci.getText().toString());
                }

                @Override
                public void afterTextChanged(Editable s) {
                    selectionStart = input_zhenbanci.getSelectionStart();
                    selectionEnd = input_zhenbanci.getSelectionEnd();
                    if (input_zhenbanci.getEditableText().toString().length() > 0) {
                        if (Float.parseFloat(input_zhenbanci.getEditableText().toString()) > 1) {
                            input_zhenbanci.setText("");
                        } else {
                            if (!WgyUtil.isOnlyonePointNumber(input_zhenbanci.getEditableText().toString())) {
                                s.delete(selectionStart - 1, selectionEnd);
                                input_zhenbanci.setText(s);
                            }
                        }
                    }

                }
            });
            item_banci.setText(item.getPROCLASS() == null ? "" : item.getPROCLASS());
            input_zhenbanci.setText(item.getSTCLASS() == null ? "" : item.getSTCLASS());
            item_gonghao.setText(item.getJOBNUM() == null ? "" : item.getJOBNUM());
            item_zhibie.setText(item.getCOTTYPE() == null ? "" : item.getCOTTYPE());
            item_shazhiquan.setText(item.getSZQC() == null ? "" : item.getSZQC());
            item_sehao.setText(item.getCOLORNO() == null ? "" : item.getCOLORNO());
            item_gonghuodanwei.setText(item.getORIPLACE() == null ? "" : item.getORIPLACE());
            item_pihao.setText(item.getBATCHNO() == null ? "" : item.getBATCHNO());
            input_shuliang.setText(item.getPACKNUM() == null ? "" : item.getPACKNUM());
            input_item_checkBox.setChecked(item.isBoxcheck());

        }
    }

    public void getDateList() {//根据日期查询是否可插入
        showWait();
        RequestServiceImpl.getdatelist(mMIPHandler, IServiceImpl.DSRCLLR_GetExistCount_M, "2018-12-09");
    }


    public void querylist(String JobDate, String ph, String zb) {//根据条件查询
        showWait();
        RequestServiceImpl.queryzhenlist(mMIPHandler, IServiceImpl.query_zhen_list, JobDate, ph, zb, userModel.getJobNum());
    }


    @Override
    public void onPostHandle(int requestType, Object objBody, boolean error) throws Exception {
        String msg = "";
        String opt = "";
        if (error) {
            if (requestType != IServiceImpl.qusha_riyongliang && requestType != IServiceImpl.qusha_chehao && requestType != IServiceImpl.qusha_pihaozhibie) {
                stopWait();
            }
            switch (requestType) {
                case IServiceImpl.DSRCLLR_GetExistCount_M://根据日期获取
                    try {
                        JSONObject jsonObj = new JSONObject((String) objBody);
                        if (jsonObj.getInt("Code") == 0) {

                        }
                    } catch (Exception e) {

                    }
                    break;
                case IServiceImpl.query_zhen_list://根据条件查询
                    try {
                        JSONObject jsonObj = new JSONObject((String) objBody);
                        if (jsonObj.getInt("Code") == 0) {
                            if (jsonObj.getJSONArray("Result") != null && jsonObj.getJSONArray("Result").length() > 0) {
                                JSONArray jsonArray = jsonObj.getJSONArray("Result");
                                daolist.clear();
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    ZhenshaModel zhenshaModel = ParseUtils.parse(jsonArray.getJSONObject(i).toString(), ZhenshaModel.class);
                                    zhenshaModel.setBoxcheck(false);
                                    zhenshaModel.setUuid(WgyUtil.getUUID());
                                    if (userModel != null) {
                                        zhenshaModel.setCREATER(userModel.getJobNum());
                                        zhenshaModel.setCRENAME(userModel.getJobName());
                                        zhenshaModel.setUPDATER(userModel.getJobNum());
                                        zhenshaModel.setUPDNAME(userModel.getJobName());
                                    }
                                    daolist.add(zhenshaModel);
                                }
                            } else {
                                daolist.clear();
                            }
                            quickAdapter.notifyDataSetChanged();
                            checkListview();

                        } else {
                            SimpleDialog.show(this, jsonObj.getString("Message"));
                        }
                    } catch (Exception e) {

                    }
                    break;
                case IServiceImpl.qusha_pihaozhibie://获取原料信息
                    try {
                        final JSONObject jsonObj = new JSONObject((String) objBody);
                        if (jsonObj.getInt("Code") == 0) {
                            doworking(jsonObj);
                        } else {
                            SimpleDialog.show(this, jsonObj.getString("Message"));
                            stopWait();
                        }
                    } catch (Exception e) {

                    }
                    break;
                case IServiceImpl.qusha_chehao://
                    try {
                        final JSONObject jsonObj = new JSONObject((String) objBody);
                        if (jsonObj.getInt("Code") == 0) {
                            doworking(jsonObj);
                        } else {
                            SimpleDialog.show(this, jsonObj.getString("Message"));
                            stopWait();
                        }
                    } catch (Exception e) {

                    }
                    break;

                case IServiceImpl.qusha_ganghao://
                    try {
                        final JSONObject jsonObj = new JSONObject((String) objBody);
                        if (jsonObj.getInt("Code") == 0) {
                            doworking(jsonObj);
                        } else {
                            SimpleDialog.show(this, jsonObj.getString("Message"));
                            stopWait();
                        }
                    } catch (Exception e) {

                    }
                    break;

                case IServiceImpl.qusha_riyongliang://获取原料信息
                    try {
                        final JSONObject jsonObj = new JSONObject((String) objBody);
                        if (jsonObj.getInt("Code") == 0) {
                            doworking(jsonObj);
                        } else {
                            SimpleDialog.show(this, jsonObj.getString("Message"));
                            stopWait();
                        }
                    } catch (Exception e) {

                    }
                    break;
                case IServiceImpl.save_zhen_list://更新
                    try {
                        JSONObject jsonObj = new JSONObject((String) objBody);
                        if (jsonObj.getInt("Code") == 0) {
                            SimpleDialog.show(this, "您已成功保存数据！");
//                            for (int i = 0; i < daolist.size(); i++) {
//                                daolist.get(i).setBoxcheck(false);
//                            }
//                            quickAdapter.notifyDataSetChanged();
                            querylist(mJobDate, queryPihao.getEditableText().toString().trim(), queryZhibie.getEditableText().toString().trim());
                        } else {
                            SimpleDialog.show(this, jsonObj.getString("Message"));
                        }
                    } catch (Exception e) {

                    }
                    break;
                case IServiceImpl.delete_zhen_list://删除成功
                    try {
                        JSONObject jsonObj = new JSONObject((String) objBody);
                        if (jsonObj.getInt("Code") == 0) {
                            SimpleDialog.show(this, "您已成功删除数据！");
                            for (int i = 0; i < deletedaolist.size(); i++) {
                                for (int j = 0; j < daolist.size(); j++) {
                                    if (daolist.get(j).getUuid().equals(deletedaolist.get(i).getUuid())) {
                                        daolist.remove(j);
                                    }
                                }
                            }
                            deletedaolist.clear();
                            quickAdapter.notifyDataSetChanged();
                            checkListview();
                        } else {
                            SimpleDialog.show(this, jsonObj.getString("Message"));
                        }
                    } catch (Exception e) {

                    }
                    break;

            }

        } else {
            stopWait();
            Toast.makeText(this, "操作失败", Toast.LENGTH_SHORT).show();

        }

    }

    public void doworking(final JSONObject jsonObj) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONArray jsonArray = jsonObj.getJSONArray("Result");
                    if (jsonArray != null && jsonArray.length() > 0) {
                        final List<ZhenshaModel> inputlist = new ArrayList<ZhenshaModel>();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            ZhenshaModel zhenshaModel = ParseUtils.parse(jsonArray.getJSONObject(i).toString(), ZhenshaModel.class);
                            zhenshaModel.setBoxcheck(false);
                            zhenshaModel.setSTCLASS("1");
                            //zhenshaModel.setPACKNUM("0");
                            zhenshaModel.setDELFLAG(0);
                            zhenshaModel.setDATASOURCE(2);
                            zhenshaModel.setJOBDATE(mJobDate);

                            if (userModel != null) {
                                zhenshaModel.setPROCLASS(userModel.getBC());
                                zhenshaModel.setJOBNUM(userModel.getJobNum());
                                zhenshaModel.setCREATER(userModel.getJobNum());
                                zhenshaModel.setCRENAME(userModel.getJobName());
                                zhenshaModel.setUPDATER(userModel.getJobNum());
                                zhenshaModel.setUPDNAME(userModel.getJobName());
                            }
                            zhenshaModel.setUuid(WgyUtil.getUUID());
                            inputlist.add(zhenshaModel);
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                DialogQusha(inputlist);
                            }
                        });

                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                stopWait();
                                SimpleDialog.show(ZhenShaActivity.this, "暂无原料信息！");
                            }
                        });
                    }

                } catch (Exception e) {

                }
            }
        }).start();
    }

    /**
     * 检查listview是否为空
     */
    private void checkListview() {
        if (daolist.size() > 0) {
            recylistview.setVisibility(View.VISIBLE);
        } else {
            recylistview.setVisibility(View.GONE);
        }
    }


    public void DialogQusha(List<ZhenshaModel> inputlist) {//取纱
        stopWait();
        dialog = new EditDialogZhen.Builder(this);
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // ;
                        dialog.selectinputlist.clear();
                        for (int j = 0; j < dialog.inputlist.size(); j++) {
                            if (dialog.inputlist.get(j).isBoxcheck()) {
                                // 添加到需要保存的列表中
                                dialog.selectinputlist.add(dialog.inputlist.get(j));
                            }
                        }
                        if (dialog.inputlist.size() == 0) {
                            SimpleDialog.show(ZhenShaActivity.this, "当前列表为空！");
                            return;
                        }

                        if (dialog.selectinputlist.size() == 0) {
                            SimpleDialog.show(ZhenShaActivity.this, "请勾选需要导入的数据！");
                            return;
                        }

                        for (ZhenshaModel daoshaModel : dialog.selectinputlist) {
                            boolean ishave = false;
                            for (ZhenshaModel havemodel : daolist) {
                                if (havemodel.getUuid().equals(daoshaModel.getUuid())) {
                                    ishave = true;
                                    break;
                                }
                            }
                            if (!ishave) {
                                daolist.add(0, daoshaModel);
                            }

                        }

                        dialogInterface.dismiss();
                        quickAdapter.notifyDataSetChanged();
                        checkListview();

                    }
                }

        ).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                }
        ).create().show();
        dialog.setDaoList(inputlist);
    }


    /**
     * 设置日期
     */
    private void setDate() {
        // 初始化日历信息
        Calendar calendar = Calendar.getInstance();
        // 获取当前年月日
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        if (hour < 7 || (hour == 7 && minute < 30)) {
            day -= 1;
        }
        Log.d("setDate", year + "-" + month + "-" + day);
        /**
         * context：当前上下文； callback：OnDateSetListener日期改变监听器； year：初始化的年；
         * monthOfYear：初始化的月（从0开始计数，所以实际应用时需要加1）； dayOfMonth：初始化的日；
         */
        DatePickerDialog datePickerDialog = new DatePickerDialog(this, mOnDateSetListenernew, year, month, day);

        datePickerDialog.show();
    }

    /**
     * 日期选择监听器
     */
    DatePickerDialog.OnDateSetListener mOnDateSetListenernew = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            String date = year + "年" + String.format("%02d", month + 1) + "月" + String.format("%02d", dayOfMonth) + "日";
            inputDateTv.setText(date);
            mJobDate = year + "-" + String.format("%02d", month + 1) + "-" + String.format("%02d", dayOfMonth);

        }
    };


    private Calendar getDefaultDate() {
        Calendar calendar = Calendar.getInstance();
        // 获取当前年月日
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
//        int hour = calendar.get(Calendar.HOUR_OF_DAY);
//        int minute = calendar.get(Calendar.MINUTE);
//        if (hour < 7 || (hour == 7 && minute < 30)) {
//            day -= 1;
//        }
        calendar.set(year, month, day);
        return calendar;
    }

    @OnClick({R.id.input_dateLl, R.id.input_searchBtn, R.id.input_deleteBtn, R.id.input_saveBtn, R.id.btnqusha_riyong, R.id.btnqusha_pizhi, R.id.btnqusha_chehao,R.id.btnqusha_ganghao})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.input_dateLl:
                setDate();
                break;
            case R.id.input_searchBtn:
                querylist(mJobDate, queryPihao.getEditableText().toString().trim(), queryZhibie.getEditableText().toString().trim());
                break;
            case R.id.input_deleteBtn:
                List<String> PKIDList = new ArrayList<String>();
                for (int i = 0; i < daolist.size(); i++) {
                    if (daolist.get(i).isBoxcheck()) {
                        deletedaolist.add(daolist.get(i));
                        // 添加到需要保存的列表中
                        if (!TextUtils.isEmpty(daolist.get(i).getPKID())) {
                            PKIDList.add(daolist.get(i).getPKID());
                        }

                    }
                }
                if (deletedaolist.size() == 0) {
                    SimpleDialog.show(this, "请勾选需要删除的数据！");
                    stopWait();
                    return;
                }
                if (daolist.size() == 0) {
                    SimpleDialog.show(this, "当前列表为空，请添加数据！");
                    stopWait();
                    return;
                }

                if (PKIDList.size() > 0) {
                    showWait();
                    RequestServiceImpl.deleteZhensha(mMIPHandler, IServiceImpl.delete_zhen_list, PKIDList, userModel.getJobNum(), userModel.getJobName());
                } else {
                    for (int i = 0; i < deletedaolist.size(); i++) {
                        for (int j = 0; j < daolist.size(); j++) {
                            if (daolist.get(j).getUuid().equals(deletedaolist.get(i).getUuid())) {
                                daolist.remove(j);
                            }
                        }
                    }
                    deletedaolist.clear();
                    quickAdapter.notifyDataSetChanged();
                }

                break;
            case R.id.input_saveBtn:
                savedaolist.clear();
                for (int i = 0; i < daolist.size(); i++) {
                    if (daolist.get(i).isBoxcheck()) {
                        // 添加到需要保存的列表中
                        savedaolist.add(daolist.get(i));
                    }
                }
                if (daolist.size() == 0) {
                    SimpleDialog.show(this, "当前列表为空，请添加数据！");
                    stopWait();
                    return;
                }

                if (savedaolist.size() == 0) {
                    SimpleDialog.show(this, "请勾选需要保存的数据！");
                    stopWait();
                    return;
                }
                for (ZhenshaModel product : savedaolist) {
                    if (TextUtils.isEmpty(product.getSTCLASS())) {
                        SimpleDialog.show(this, "蒸纱班次不能为空！");
                        stopWait();
                        return;
                    }
                    if (Float.parseFloat(product.getSTCLASS()) == 0) {
                        SimpleDialog.show(this, "蒸纱班次不能为0！");
                        stopWait();
                        return;
                    }
                    if (TextUtils.isEmpty(product.getPACKNUM())) {
                        SimpleDialog.show(this, "数量不能为空！");
                        stopWait();
                        return;
                    }

                    if (Float.parseFloat(product.getPACKNUM()) == 0) {
                        SimpleDialog.show(this, "数量不能为0！");
                        stopWait();
                        return;
                    }

                }

                showWait();
                RequestServiceImpl.updateZhensha(mMIPHandler, IServiceImpl.save_zhen_list, savedaolist);
                break;
            case R.id.btnqusha_riyong:
                showWait();
                RequestServiceImpl.getYuanliaoInfo_sha_riyongliang(mMIPHandler, IServiceImpl.qusha_riyongliang, dateFormat_EN.format(getDefaultDate().getTime()));
                break;
            case R.id.btnqusha_pizhi:
                if (quPihao.getEditableText().toString().trim().length() == 0 && quZhibie.getEditableText().toString().trim().length() == 0) {
                    SimpleDialog.show(this, "请输入批号或支别");
                    return;
                }
                showWait();
                RequestServiceImpl.getYuanliaoInfo_sha_pihao(mMIPHandler, IServiceImpl.qusha_pihaozhibie, quPihao.getEditableText().toString().trim(), quZhibie.getEditableText().toString().trim());
                break;
            case R.id.btnqusha_chehao:
                showWait();
                RequestServiceImpl.getYuanliaoInfo_sha_chehao(mMIPHandler, IServiceImpl.qusha_chehao, quChehao.getEditableText().toString().trim());

                break;
            case R.id.btnqusha_ganghao:
                if (quGanghao.getEditableText().toString().trim().length() == 0) {
                    SimpleDialog.show(this, "请输入缸号");
                    return;
                }
                showWait();
                RequestServiceImpl.getYuanliaoFromGaohao(mMIPHandler, IServiceImpl.qusha_ganghao, quGanghao.getEditableText().toString().trim());

                break;


        }
    }
}
